import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
import message from 'element-ui/packages/message'
import {error} from "autoprefixer/lib/utils";

const service = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 100000
})

service.interceptors.request.use((config) => {
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

service.interceptors.response.use(async(response) => {
  const { code, msg } = response.data
  if (code === 200) {
    return response.data
  } else {
    if (response.data.code === 401) {
      Message({ type: 'warning', message: 'token 过期' })
      // 退出登录
      await store.dispatch('user/logout')
      // 主动跳转到登录页
      router.push('/login')
      return Promise.reject(error)
    }
    Message({ type: 'error', message: msg })
    return Promise.reject(new Error(msg))
  }
}, (error) => {
  Message({ type: 'error', message: error.msg })
  return Promise.reject(error)
})

export default service
